package file

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/errcode"
	pb "git.mycaigou.com/gfyx/micro-gfyx-user-service/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/service/file"
	"git.myscrm.cn/golang/common/ykerrcode"
)

type FileServer struct {
	FileService file.FileServiceIface
}

func NewFileServer(fileService file.FileServiceIface) pb.FileServiceServer {
	return &FileServer{
		FileService: fileService,
	}
}

func (s *FileServer) SaveToFile(ctx context.Context, request *pb.SaveToFileRequest) (*pb.SaveToFileResponse, error) {
	var response = &pb.SaveToFileResponse{}
	if request.FileName == "" || request.FilePath == "" || request.Business == "" || request.FileType == "" {
		return response, ykerrcode.TogRPCError(errcode.COMMON_PARAMS_ERROR)
	}
	uid, err := s.FileService.SaveToFile(ctx, request.FilePath, request.FileType, request.FileName, request.Business, request.FileSize, request.IsPrivate, request.TenantCode)
	response.FileUid = uid
	if err != nil {
		return response, err
	}
	return response, nil
}

func (s *FileServer) GetFileInfo(ctx context.Context, request *pb.GetFileInfoRequest) (*pb.GetFileInfoResponse, error) {
	resp := &pb.GetFileInfoResponse{}

	fileInfo, err := s.FileService.QueryByUid(ctx, request.FileUid)
	if err != nil {
		return resp, err
	}
	if fileInfo == nil {
		return resp, errors.New("文件uid对应不存在")
	}
	resp.FileInfo = &pb.FileInfo{
		FileUid:      fileInfo.Uid,
		TenantCode:   fileInfo.TenantCode,
		Business:     fileInfo.Business,
		FileName:     fileInfo.FileName,
		FileType:     fileInfo.FileType,
		FilePath:     fileInfo.FilePath,
		FileSize:     fileInfo.FileSize,
		IsPrivate:    int32(fileInfo.IsPrivate),
		CreatedTime:  fileInfo.CreatedOn.Format("2006-01-02 15:04:05"),
		ModifiedTime: fileInfo.ModifiedOn.Format("2006-01-02 15:04:05"),
	}

	return resp, nil
}
